﻿// MainFormDlg.cpp : 구현 파일입니다.
//

#include "stdafx.h"
#include "AutomotivAirMonitor.h"
#include "MainFormDlg.h"
#include "afxdialogex.h"
#include "DataLoadDlg.h"
#include "FileNameInpuDlg.h"

// CMainFormDlg 대화 상자입니다.

IMPLEMENT_DYNAMIC(CMainFormDlg, CDialogEx)

CMainFormDlg::CMainFormDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CMainFormDlg::IDD, pParent)
	, m_strCommState(_T(""))
{
	m_bListUpdate = FALSE;
	m_bSaveFlag = FALSE;
	nSaveCnt = 0;
	m_bDataWriteFlag = FALSE;
	m_pListupThread = NULL;
	m_pLoggingThread = NULL;
	m_nEmergency_listflag = 0;
	m_nEmergency_logflag = 0;
	for(int i=0; i<MAX_SENSORS;i++)
		m_bShowGraph[i] = TRUE;
	m_bListclear = FALSE;
	m_bReceived = FALSE;
	m_nTimeoutCnt = 5;
	m_strElapseTime = L"00:00:00";
	m_bSaveStarted = FALSE;
	m_strLogFileName = L"";
	m_bAnalysis = FALSE;

	m_nAnalysisResult = 0;
	m_strAnalysisMsg[0] = L"냄새가 사라짐!";
	m_strAnalysisMsg[1] = L"냄새가 나기 시작함!";
	m_strAnalysisMsg[2] = L"냄새가 심함!";

	m_strAnalysisMsg2[0] = L"냄새없음";
	m_strAnalysisMsg2[1] = L"냄새발생";
	
	m_maxHumidity = 0;
	m_Logic6_Temper1[0]=0;
	m_Logic6_Temper1[1]=0;
	m_Logic6_Temper2[0]=0;
	m_Logic6_Temper2[1]=0;
}

CMainFormDlg::~CMainFormDlg()
{	
	for(int i=0;i<5; i++){
		delete m_pBtnEmergencys[i];	
	}
}

void CMainFormDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_BUTTON_SENSOR1, m_sensor1);
	DDX_Control(pDX, IDC_BUTTON_COMM, m_cBtnComm);
	DDX_Text(pDX, IDC_STATIC_COMMSTATE, m_strCommState);
	DDX_Control(pDX, IDC_LIST_TEMPERATURE, m_cListTemper);
	DDX_Control(pDX, IDC_LIST_HUMIDITY, m_cListHumi);
	DDX_Control(pDX, IDC_STATIC_DATAFRAME, m_cStaticDataframe);
	DDX_Control(pDX, IDC_STATIC_SENSORNAMETAG, m_cStaticSensorNameTag);
	DDX_Control(pDX, IDC_BUTTON_EMERGENCY, m_cBtnEmergency);
	DDX_Control(pDX, IDC_STATIC_EMERGENCYZONE, m_cEmergencyzone);
	DDX_Control(pDX, IDC_BUTTON_LOGOPEN, m_cLogopenBtn);	
	DDX_Control(pDX, IDC_CHECK_SETLOG, m_cLogChecked);
	DDX_Control(pDX, IDC_BUTTON_LOGSTART, m_cLogsaveStartbtn);
	DDX_Control(pDX, IDC_COMBO_SELECTID, m_cComboIDSelect);
	DDX_Control(pDX, IDC_BUTTON_ANALYSIS, m_cBtnAnalysis);
	DDX_Control(pDX, IDC_COMBO_SELECTLOGIC, m_cComboSelectLogic);
	DDX_Control(pDX, IDC_EDIT_LOGICVARIABLE, m_cEditLogicValue);
	DDX_Control(pDX, IDC_COMBO_SELECTID2, m_cComboIDSelect2);
}


BEGIN_MESSAGE_MAP(CMainFormDlg, CDialogEx)
	ON_WM_CREATE()
	ON_BN_CLICKED(IDC_BUTTON_OPENFOLDER, &CMainFormDlg::OnBnClickedButtonOpenfolder)
	ON_CONTROL_RANGE(BN_CLICKED, 10100, 10100 + 110, OnBtnClicked)
	ON_BN_CLICKED(IDC_BUTTON_COMM, &CMainFormDlg::OnBnClickedButtonComm)
	ON_MESSAGE(WM_COMM_READ, OnRcvData)	
	ON_BN_CLICKED(IDC_RADIO_TEMPER, RadioChecked)
	ON_BN_CLICKED(IDC_RADIO_HUMI, RadioChecked)
	ON_WM_TIMER()
	ON_WM_DESTROY()
	ON_NOTIFY(NM_CUSTOMDRAW, IDC_LIST_TEMPERATURE, OnCustomdrawList)
	ON_NOTIFY(NM_CUSTOMDRAW, IDC_LIST_HUMIDITY, OnCustomdrawList)
	ON_BN_CLICKED(IDC_BUTTON_EMERGENCY, &CMainFormDlg::OnBnClickedButtonEmergency)
	ON_WM_PAINT()
	ON_WM_CTLCOLOR()
	ON_NOTIFY(HDN_ITEMCLICK, 0, &CMainFormDlg::OnHdnItemclickListTemperature)
	ON_STN_CLICKED(IDC_STATIC_IMAGE, &CMainFormDlg::OnStnClickedStaticImage)
	ON_BN_CLICKED(IDC_BUTTON_LOGOPEN, &CMainFormDlg::OnBnClickedButtonLogopen)
	ON_BN_CLICKED(IDC_BUTTON_LOGSTART, &CMainFormDlg::OnBnClickedButtonLogstart)
	ON_BN_CLICKED(IDC_BUTTON_ANALYSIS, &CMainFormDlg::OnBnClickedButtonAnalysis)
	ON_CBN_SELCHANGE(IDC_COMBO_SELECTID, &CMainFormDlg::OnCbnSelchangeComboSelectid)
	ON_CBN_SELCHANGE(IDC_COMBO_SELECTID2, &CMainFormDlg::OnCbnSelchangeComboSelectid2)
	ON_CBN_SELCHANGE(IDC_COMBO_SELECTLOGIC, &CMainFormDlg::OnCbnSelchangeComboSelectlogic)
	ON_CBN_SETFOCUS(IDC_COMBO_SELECTID2, &CMainFormDlg::OnCbnSetfocusComboSelectid2)
	ON_CBN_SETFOCUS(IDC_COMBO_SELECTID, &CMainFormDlg::OnCbnSetfocusComboSelectid)
	ON_CBN_SETFOCUS(IDC_COMBO_SELECTLOGIC, &CMainFormDlg::OnCbnSetfocusComboSelectlogic)
END_MESSAGE_MAP()


// CMainFormDlg 메시지 처리기입니다.

int CMainFormDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CDialogEx::OnCreate(lpCreateStruct) == -1)
		return -1;

	// TODO:  여기에 특수화된 작성 코드를 추가합니다.
	this->MoveWindow(0,0,1024,700);

	return 0;
}
void CMainFormDlg::_createThread()
{	
	m_pListupThread = ::AfxBeginThread(listUpdate,this);		
 	m_pListupThread->SuspendThread();
	if(m_pListupThread == NULL)
	{
		AfxMessageBox(L"쓰레드 생성 실패");		
	}

	m_pLoggingThread = ::AfxBeginThread(xlslogging,this);
	m_pLoggingThread->SuspendThread();
	if(m_pLoggingThread == NULL)
	{
		AfxMessageBox(L"쓰레드 생성 실패");		
	}
}

UINT CMainFormDlg::xlslogging(LPVOID pParam)
{		

	CMainFormDlg *pDlg = (CMainFormDlg*)pParam;

	CString strTemp=L"",strMsg=L"", strFilepath=L"";
	COleDateTime tNow;

	//  [6/1/2012 %bume%]
	// 로그파일 이름입력
	if(pDlg->m_strLogFileName.GetLength() >0){
		strTemp.Format(L"%s\\%s",_T(LOGPATH),pDlg->m_strLogFileName);
	}
	else{
		tNow = COleDateTime::GetCurrentTime();
		strTemp.Format(L"%s\\%04d%02d%02d_%02d%02d",_T(LOGPATH),tNow.GetYear(), tNow.GetMonth(), tNow.GetDay(), tNow.GetHour(), tNow.GetMinute());
	}
	strFilepath = strTemp + L".csv";

	while(pDlg->m_comm.m_bConnected)
	{
		if(!pDlg->m_cLogChecked.GetCheck())
			continue;		
		if(!pDlg->m_bSaveStarted)
			continue;
		tNow = COleDateTime::GetCurrentTime();		
		if(pDlg->m_bSaveFlag){
			if(pDlg->m_strLogFileName.GetLength() >0){
				strTemp.Format(L"%s\\%s",_T(LOGPATH),pDlg->m_strLogFileName);
			}
			else{
				strTemp.Format(L"%s\\%04d%02d%02d_%02d%02d",_T(LOGPATH),tNow.GetYear(), tNow.GetMonth(), tNow.GetDay(), tNow.GetHour(), tNow.GetMinute());
			}
			strFilepath = strTemp + L".csv";
			pDlg->m_bSaveFlag = FALSE;

		}
		if(pDlg->m_bDataWriteFlag)
		{			
			CFile cfile(strFilepath,CFile::modeCreate | CFile::modeNoTruncate | CFile::modeReadWrite | CFile::modeNoInherit);
			if(cfile.GetLength() <= 0){
				strMsg += L"Time,EmergencyLV";
				for(int i=0;i<MAX_SENSORS;i++){
					strTemp.Format(L",ID%d_Temper,ID%d_Humi",i+1,i+1);
					strMsg+= strTemp;
				}
				strMsg += "\r\n";
				cfile.Write(strMsg,strMsg.GetLength()*2);
			}
			cfile.SeekToEnd();
			strMsg = L"";	
			strTemp.Format(L"%02d:%02d:%02d",tNow.GetHour(), tNow.GetMinute(), tNow.GetSecond());
						strMsg += strTemp;
						if(pDlg->m_nEmergency_logflag > 0)
						{
							strTemp.Format(L"%d",pDlg->m_nEmergency_logflag);
							strMsg += L","+strTemp;
						}
						else
							strMsg += L",-";
						for(int i=0; i<MAX_SENSORS; i++){
							if(pDlg->m_sensorDatas[i].ID <= MAX_SENSORS)
							{
								strTemp.Format(L",%.1f,%.1f", pDlg->m_sensorDatas[i].TEMPERATURE, pDlg->m_sensorDatas[i].HUMIDITY);
								strMsg += strTemp;
							}
							else
							{
								strMsg += L",0,0";
							}
			
						}					
			strMsg += L"\r\n";
			cfile.Write(strMsg,strMsg.GetLength()*2);
			cfile.Close();
			strMsg = L"";
			pDlg->m_nEmergency_logflag = 0;
			pDlg->m_bDataWriteFlag = FALSE;
		}
		Sleep(0);
	}
	return 0;	
}

UINT CMainFormDlg::listUpdate(LPVOID pParam)
{
	CMainFormDlg *pDlg = (CMainFormDlg*)pParam;
	CString strTemp=L"",strMsg=L"";
	COleDateTime tNow;
	int nTimeoutcnt=0;
	
	while(pDlg->m_comm.m_bConnected){
		tNow = COleDateTime::GetCurrentTime();			
		if(pDlg->m_bListUpdate)
		{			
			strTemp.Format(L"%02d:%02d:%02d",tNow.GetHour(), tNow.GetMinute(), tNow.GetSecond());
			int nIdx = pDlg->m_cListTemper.GetItemCount();
			if(nIdx < 0)
				nIdx = 0;
			//클리어 리스트
			if(pDlg->m_bListclear)
			{
				pDlg->ClearList();				
				nIdx = 0;
				pDlg->m_bListclear = FALSE;
			}

			pDlg->m_cListTemper.InsertItem(0,strTemp,0);
			pDlg->m_cListHumi.InsertItem(0,strTemp,0);
			

			for(int i=0; i<MAX_SENSORS; i++){
				int nId = pDlg->m_sensorDatas[i].ID-1;
				if(nId >= 0 && nId < MAX_SENSORS) //ID 유효성 검사
				{
					//pDlg->m_pSensors[nId]->putSensorData(pDlg->m_sensorDatas[i].ID, pDlg->m_sensorDatas[i].TEMPERATURE, pDlg->m_sensorDatas[i].HUMIDITY);

					if(pDlg->m_sensorDatas[i].TEMPERATURE == -1){
						strMsg = L"";
					}
					else{
						strMsg.Format(L"%.1f",pDlg->m_sensorDatas[i].TEMPERATURE);
					}
					pDlg->m_cListTemper.SetItemText(0,pDlg->m_sensorDatas[i].ID+1,strMsg);

					if(pDlg->m_sensorDatas[i].HUMIDITY == -1){
						strMsg = L"";
					}
					else{
						strMsg.Format(L"%.1f",pDlg->m_sensorDatas[i].HUMIDITY);
					}
					pDlg->m_cListHumi.SetItemText(0,pDlg->m_sensorDatas[i].ID+1,strMsg);

 					if(pDlg->m_nEmergency_listflag > 0)
 					{
 						pDlg->m_cListTemper.SetItemText(0,1,L"  X");
 						pDlg->m_cListHumi.SetItemText(0,1,L"  X");
 					}
 					else
 					{
 						pDlg->m_cListTemper.SetItemText(0,1,L"  -");
 						pDlg->m_cListHumi.SetItemText(0,1,L"  -");
 					}
				}
			}
			pDlg->m_nEmergency_listflag = 0;
			pDlg->m_bListUpdate = FALSE;
		}
		Sleep(0);
	}	
	return 0;
}
void CMainFormDlg::createUI()
{
	CRect rect,rtGraph,rtSensor,rtEmerBtn;
	GetClientRect(rect);	
	CopyRect(rtGraph,rect);
	int nWid = rect.Width();
	int nHei = rect.Height();
	int offset_x=15, offset_y = 80;
	int sensorWidth = 140, sensorHeight = 50;
	int listWidth = 500, listHeight = 250;
	int nHcnt=0;
	int nGab = 20;	
	
	m_cStaticSensorNameTag.ShowWindow(SW_HIDE);
	/*
	// 센서그룹
	m_cStaticSensorNameTag.MoveWindow(offset_x, offset_y*1.8-(nGab*2),sensorWidth*3+10,listHeight+50);
	//센서
	for(int i=0; i<10; i++){
		if(i<4){
			rtSensor.left = offset_x+10;
			rtSensor.right = offset_x+sensorWidth;
		}
		else if(i<8)
		{
			rtSensor.left = offset_x+sensorWidth+10;
			rtSensor.right = offset_x+sensorWidth*2;
		}
		else{
			rtSensor.left = offset_x+(sensorWidth*2)+10;
			rtSensor.right = offset_x+sensorWidth*3;
		}		
		rtSensor.top = offset_y*1.5+(sensorHeight*(i%4))+10;
		rtSensor.bottom = offset_y*1.5+(sensorHeight*((i%4)+1));		
				
		//m_pSensors[i] = new CSensorNode();
		//m_pSensors[i]->Create(NULL, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,rtSensor,this,10100+i);
	}
	*/
	
	// 포트연결 버튼
	m_cBtnComm.MoveWindow(nWid*0.25,nHei*0.08,0,0);
	m_cBtnComm.LoadBitmaps(IDB_OPENCOMM_DIS,IDB_OPENCOMM_SEL,NULL,IDB_OPENCOMM_DIS);
	m_cBtnComm.SizeToContent();


	//logopen 버튼
	m_cLogopenBtn.MoveWindow(nWid*0.25,nHei*0.175,0,0);
	m_cLogopenBtn.LoadBitmaps(IDB_LOGOPEN_DIS,IDB_LOGOPEN_SEL,NULL,IDB_LOGOPEN_DIS);
	m_cLogopenBtn.SizeToContent();

	//logsave 버튼
	m_cLogsaveStartbtn.MoveWindow(nWid*0.18,nHei*0.175,0,0);
	m_cLogsaveStartbtn.LoadBitmaps(IDB_LOGSAVESTART_DIS,IDB_LOGSAVESTART_SEL,NULL,IDB_LOGSAVESTART_DIS);
	m_cLogsaveStartbtn.SizeToContent();

	//logcheckbox
	m_cLogChecked.MoveWindow(50,165,20,20);
	m_cLogChecked.SetCheck(TRUE);

	//  [6/17/2012 Bume]	
	// 분석 버튼
	m_cBtnAnalysis.MoveWindow(35,nHei*0.39,0,0);
	m_cBtnAnalysis.LoadBitmaps(IDB_BTNANALYSIS_S_DIS,IDB_BTNANALYSIS_S_SEL,NULL,IDB_BTNANALYSIS_S_DIS);
	m_cBtnAnalysis.SizeToContent();

	m_cComboSelectLogic.MoveWindow(nWid*0.09,nHei*0.39+2,35,25);
	m_cComboIDSelect.MoveWindow(nWid*0.13,nHei*0.39+2,40,25);
	m_cComboIDSelect2.MoveWindow(nWid*0.17,nHei*0.39+2,40,25);	
	m_cEditLogicValue.MoveWindow(nWid*0.21,nHei*0.39+2,35,25);

	// 이머전시 버튼
	//m_cEmergencyzone.MoveWindow(sensorWidth*2-10,10,350,63);
	for(int i=0; i<5; i++)
	{
		rtEmerBtn.left = (i*60)+35;
		rtEmerBtn.top = 195;
		m_pBtnEmergencys[i] = new CBitmapButton();
		m_pBtnEmergencys[i]->Create(NULL, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW, rtEmerBtn, this, 10200+i);
		m_pBtnEmergencys[i]->LoadBitmaps(IDB_EMERGENCY_LV1_DIS+i,IDB_EMERGENCY_LV1_SEL+i,NULL,IDB_EMERGENCY_LV1_DIS+i);
		m_pBtnEmergencys[i]->SizeToContent();
	}	
	m_cBtnEmergency.LoadBitmaps(IDB_EMERGENCY_DISABLE,IDB_EMERGENCY_PUSH,NULL,IDB_EMERGENCY_DISABLE);
	m_cBtnEmergency.SizeToContent();
	m_cBtnEmergency.ShowWindow(SW_HIDE);

	//온,습도 라디오 버튼
	CButton *pRadio;
	pRadio = (CButton *)GetDlgItem(IDC_RADIO_TEMPER);
	pRadio->SetCheck(TRUE);	
	pRadio->MoveWindow(sensorWidth*4-nGab+30, 20,80, 20);
	SetWindowTheme(pRadio->m_hWnd, L"", L"");

	pRadio = (CButton *)GetDlgItem(IDC_RADIO_HUMI);
	pRadio->MoveWindow(sensorWidth*4-nGab+120, 20,80, 20);	
	SetWindowTheme(pRadio->m_hWnd, L"", L"");

	pRadio = (CButton *)GetDlgItem(IDC_CHECK_SETLOG);
	SetWindowTheme(pRadio->m_hWnd, L"", L"");

	
	// 리스트 그룹
	//m_cStaticDataframe.MoveWindow(sensorWidth*3+(nGab)+10, offset_y*1.8-(nGab*2),listWidth+(nGab*2), listHeight+50);
	//온도 리스트	
	m_cListTemper.MoveWindow(sensorWidth*3+(nGab*2), offset_y,listWidth , listHeight);	
	CString strMsg;
	m_cListTemper.InsertColumn(0,L"시간",0,60);
	m_cListTemper.InsertColumn(1,L"이상상태",0,60);
	for(int i=1; i<MAX_SENSORS+1; i++){
		strMsg.Format(L"ID %d",i);
		m_cListTemper.InsertColumn(i+1,strMsg,0,40);		
	}
	//습도 리스트
	m_cListHumi.MoveWindow(sensorWidth*3+(nGab*2), offset_y,listWidth, listHeight);
	m_cListHumi.InsertColumn(0,L"시간",0,60);
	m_cListHumi.InsertColumn(1,L"이상상태",0,60);
	for(int i=1; i<MAX_SENSORS+1; i++){
		strMsg.Format(L"ID %d",i);
		m_cListHumi.InsertColumn(i+1,strMsg,0,40);		
	}
	m_cListHumi.ShowWindow(SW_HIDE);
	
	//온도그래프
	rtGraph.left = offset_x;
	rtGraph.top = rect.Height()/2;
	rtGraph.right = rect.Width()/2-offset_x;
	rtGraph.bottom = rect.Height()-offset_y;
	m_chartTemper.m_cChartConfig.dblAxisYMax = 50;
	m_chartTemper.m_cChartConfig.dblAxisYMin = 0;	
	m_chartTemper.m_cChartConfig.szAxisYNM = L"Temperature(℃)";
	m_chartTemper.m_cChartConfig.szAxisXNM = L"Time";
	m_chartTemper.Create(NULL,NULL,WS_CHILD | WS_VISIBLE,rtGraph,this,1);
	
	//습도그래프
	rtGraph.left = rect.Width()/2;
	rtGraph.top = rect.Height()/2;
	rtGraph.right = rect.Width()-(offset_x*2);
	rtGraph.bottom = rect.Height()-offset_y;
	m_chartHumi.m_cChartConfig.dblAxisYMax = 100;
	m_chartHumi.m_cChartConfig.dblAxisYMin = 0;
	m_chartHumi.m_cChartConfig.szAxisYNM = L"Humidity(%)";
	m_chartHumi.m_cChartConfig.szAxisXNM = L"Time";
	//m_chartHumi.m_cChartConfig.szFormat = "%03d";
	m_chartHumi.Create(NULL,NULL,WS_CHILD | WS_VISIBLE,rtGraph,this,2);

	//SetWindowTheme(m_cComboIDSelect.GetSafeHwnd(), L"", L"");		

	CreateDirectory(_T(LOGPATH), NULL);
}

BOOL CMainFormDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// TODO:  여기에 추가 초기화 작업을 추가합니다.
	createUI();
	m_comm.SetreturnHandle(this->m_hWnd);
	m_strCommState.Format(L"연결끊김");
	_createThread();
	UpdateData(FALSE);
	m_cComboIDSelect.SetCurSel(0);
	m_cComboSelectLogic.SetCurSel(0);
	m_nLogic = LOGIC_1;
	OnCbnSelchangeComboSelectlogic();
	return TRUE;  // return TRUE unless you set the focus to a control
	// 예외: OCX 속성 페이지는 FALSE를 반환해야 합니다.
}
void CMainFormDlg::makeLogfile()
{
	

}

void CMainFormDlg::OnBnClickedButtonOpenfolder()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	CApplication excelApp;
	CWorkbook wBook;
	CWorkbooks wBooks;
	CWorksheets wSheets;
	CWorksheet wSheet;
	COleVariant VOptionl((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
	COleVariant VFalse((short)FALSE);
	if(!excelApp.CreateDispatch(L"Excel.Application"))
	{
		MessageBox(L"엑셀 초기화 실패");
		return ;
	}
	else
	{
		wBooks = excelApp.get_Workbooks();
		wBook = wBooks.Add(VOptionl);
		wSheets = wBook.get_Sheets();
		wSheet = wSheets.get_Item(COleVariant((short)1));
		wSheet.Activate();		

		CRange range;

		range = wSheet.get_Range(COleVariant(L"B2"),COleVariant(L"B6"));
		range.put_Value2(COleVariant(L"Hello"));
		
		wBook.SaveAs(COleVariant(L"d:\\1243.xls"),
			COleVariant((long)-4143),
			COleVariant(L"",VT_BSTR),
			COleVariant(L"",VT_BSTR),
			VFalse, VFalse, 1, VOptionl, VOptionl, VOptionl, VOptionl, VOptionl);

		wBook.Close(COleVariant((short)FALSE),VOptionl,VOptionl);
		excelApp.Quit();

		wBook.ReleaseDispatch();
		wBooks.ReleaseDispatch();
		excelApp.ReleaseDispatch();

	}
	excelApp.put_Visible(FALSE);
	excelApp.put_DisplayAlerts(TRUE);
}

void CMainFormDlg::OnBtnClicked(UINT nId)
{	
	//센서클릭 이벤트
	if(nId < 10200)
	{
		int nSenserId = nId - 10100;
		m_bShowGraph[nSenserId] = !m_bShowGraph[nSenserId];

		m_chartTemper.m_ChartData[nSenserId].m_config.bShowDataLine = m_bShowGraph[nSenserId];
		m_chartHumi.m_ChartData[nSenserId].m_config.bShowDataLine = m_bShowGraph[nSenserId];
	}
	
	else if(nId >= 10200)
	{
		int nLv = nId - 10200;
		CString strMsg;
		m_nEmergency_logflag = nLv+1;

		strMsg.Format(L"  %d",nLv+1);
		m_cListTemper.SetItemText(0,1,strMsg);
		m_cListHumi.SetItemText(0,1,strMsg);
		m_chartTemper.SetWarning(nLv);	
		m_chartHumi.SetWarning(nLv);
		
		//  [6/17/2012 Bume]
		// 냄새 경보 test code
		/*
		if(nLv == 1)
			m_nAnalysisResult = 0;
		else if(nLv == 2)
			m_nAnalysisResult = 1;
		else if(nLv == 3)
			m_nAnalysisResult = 2;
			*/
	}

	

}

void CMainFormDlg::getUsefulport()
{
	CString strReg=L"";
	DWORD dwType = REG_SZ;
	DWORD dwSize = 128;
	HKEY hKey;
	TCHAR szBuffer[128] = {'\0',};
	TCHAR i_str[MAX_PATH];
	DWORD size = MAX_PATH;
	LONG regRead = -1;
	
	int count = 0;
	LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"HARDWARE\\DEVICEMAP\\SERAILCOMM", 0, KEY_READ | KEY_QUERY_VALUE, &hKey);
	if(lResult == ERROR_SUCCESS)
	{		
		for(int i=0; lResult == ERROR_SUCCESS; i++)
		{
			lResult = RegEnumValue(hKey, i, i_str, &size, NULL, NULL, NULL, NULL);
			if(lResult == ERROR_SUCCESS){
				RegQueryValueEx(hKey,i_str, 0, &dwType,(LPBYTE)szBuffer,&dwSize);
				AfxMessageBox(szBuffer);
			}
			size = MAX_PATH;
		}
		RegCloseKey(hKey);
	}
	return;
}

CString CMainFormDlg::getSerialPort()
{
	CString strPort;
	HKEY hKey;
	TCHAR buffer[_MAX_PATH];
	DWORD dwType, dwByte;
	LONG result;
	int nPort;

	result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,L"HARDWARE\\DEVICEMAP\\SERIALCOMM",0,KEY_ALL_ACCESS,&hKey);
	if(result == ERROR_SUCCESS)
	{		
		for(int j=0; j<3; j++)
		{			
			int i=0;
			CString strSubkey;
			for(int i=0; i<10; i++)
			{
				if(j==0)
					strSubkey.Format(L"\\Device\\cyg_ser%d",i);
				else if(j==1)
					strSubkey.Format(L"\\Device\\slabser%d",i);
				else if(j==2)
					strSubkey.Format(L"\\Device\\Silabser%d",i);

				result = RegQueryValueEx(hKey,strSubkey,NULL,&dwType,(unsigned char*)buffer,&dwByte);
				if(result == ERROR_SUCCESS)
				{ 				
					nPort = _wtoi(&buffer[3]);					
				}
			}
		}		
	}

	if(nPort > 4)
		strPort.Format(L"\\\\.\\COM%d",nPort);
	else
		strPort.Format(L"COM%d",nPort); 

	RegCloseKey(hKey);

	return strPort;
}

void CMainFormDlg::OnBnClickedButtonComm()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	CString strPort;
	int len;
	strPort = getSerialPort();
	len = strPort.GetLength();
	//AfxMessageBox(strPort);
	//  [1/3/2012 sbhwang]
	// 포트강제할당
	//strPort = L"COM3";
	//strPort = L"\\\\.\\COM7";
	//////////////////////////////////////////////////////////////////////////
	if(!m_comm.m_bConnected){
			if(m_comm.OpenPort(strPort,CBR_115200,8,2,0))
			{
				//m_cBtnComm.SetWindowText(L"통신종료");
				m_cBtnComm.LoadBitmaps(IDB_CLOSECOMM_DIS,IDB_CLOSECOMM_SEL,NULL,IDB_CLOSECOMM_DIS);
				if(len > 4)
					m_strCommState.Format(L"%s 연결됨", strPort.Mid(4,len));
				else
					m_strCommState.Format(L"%s 연결됨", strPort);				
				ClearList();
				ClearSensor();
				m_bSaveFlag = TRUE;
				m_pListupThread->ResumeThread();
				m_pLoggingThread->ResumeThread();
				//SetTimer(TIMELOG,600000,NULL);
				SetTimer(MONITERRING_UPDATE, 1000, NULL);				
			}		
			else
			{
				AfxMessageBox(L"연결 할 수 없습니다. 수신기의 연결상태를 확인해 주십시오.");
			}
		}
		else{
			m_pListupThread->SuspendThread();
			m_pLoggingThread->SuspendThread();
			m_comm.ClosePort();
			//m_cBtnComm.SetWindowText(L"통신연결");
			m_cBtnComm.LoadBitmaps(IDB_OPENCOMM_DIS,IDB_OPENCOMM_SEL,NULL,IDB_OPENCOMM_DIS);			
			m_strCommState.Format(L"연결끊김");
			m_bAnalysis = FALSE;
			OnBnClickedButtonAnalysis();
			//ClearSensor();
			//  [1/4/2012 sbhwang] : 데이터 refresh 없음
			//	KillTimer(TIMELOG);		
			
			KillTimer(MONITERRING_UPDATE);
		}	
	UpdateData(FALSE);	
	Invalidate(FALSE);
}

LRESULT CMainFormDlg::OnRcvData(WPARAM wParam, LPARAM lParam)
{	
	int nOILv = (int)wParam;
	
	//리모컨 데이터
	if(wParam > 0){
		//버튼클릭 함수를 이용하기 위해 ID값을 더해줌
		OnBtnClicked(nOILv+10199);
	}
	// 센서 데이터
	else{
		SENSORDATA *tempBuf = m_comm.GetRCVdata();
		// 그래프 데이터 입력
		for(int i=0; i<MAX_SENSORS; i++){
			int nId = tempBuf[i].ID-1;
			if(nId >= 0 && nId < MAX_SENSORS)	//ID 유효성 검사, 유효장치 카운트
			{
				m_sensorDatas[nId].ID = nId+1;
				//m_sensorDatas[nId].TEMPERATURE = tempBuf[i].TEMPERATURE;
				m_sensorDatas[nId].TEMPERATURE = tempBuf[i].TEMPERATURE > 50 ? -1 : tempBuf[i].TEMPERATURE;
				//m_sensorDatas[nId].HUMIDITY = tempBuf[i].HUMIDITY;
				m_sensorDatas[nId].HUMIDITY = tempBuf[i].HUMIDITY > 100 ? -1 : tempBuf[i].HUMIDITY;
			}
		}
		m_bReceived = TRUE;
		m_nTimeoutCnt = 5;
	}
	
	return 1;
}



void CMainFormDlg::ClearSensor()
{
	for(int i=0;i<MAX_SENSORS; i++){
		//m_pSensors[i]->intitailSensor();
		m_chartTemper.Clear();
		m_chartHumi.Clear();
	}
	m_chartTemper.RedrawWindow();
	m_chartHumi.RedrawWindow();
}

void CMainFormDlg::ClearList()
{
	m_cListTemper.DeleteAllItems();
	m_cListHumi.DeleteAllItems();
}

void CMainFormDlg::RadioChecked()
{
	int m_nRadioBtns = GetCheckedRadioButton(IDC_RADIO_TEMPER,IDC_RADIO_HUMI);
	switch (m_nRadioBtns)
	{
	case IDC_RADIO_TEMPER: 
		m_cListHumi.ShowWindow(SW_HIDE);
		m_cListTemper.ShowWindow(SW_SHOW);
		break;
	case IDC_RADIO_HUMI:
		m_cListTemper.ShowWindow(SW_HIDE);
		m_cListHumi.ShowWindow(SW_SHOW);
		break;
	default:
		break;
	}
}

void CMainFormDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다.
	if(nIDEvent == TIMELOG){
		m_bSaveFlag = TRUE;
		m_bListclear = TRUE;
		for(int i=0; i<MAX_SENSORS; i++){
			m_chartTemper.m_ChartData[i].Clear(1);
			m_chartHumi.m_ChartData[i].Clear(1);
		}						
	}
	else if(nIDEvent == MONITERRING_UPDATE){
		if(m_comm.m_bConnected && m_bReceived)
		{
			m_nTimeoutCnt--;
			if(m_nTimeoutCnt == 0){
				m_bReceived = FALSE;				
			}
			CString strTemp;
			COleDateTime tNow(COleDateTime::GetCurrentTime());	
			strTemp = tNow.Format(L"%H:%M:%S");
			//strTemp.Format(L"%02d:%02d:%02d",tNow.GetHour(), tNow.GetMinute(), tNow.GetSecond());
			
			//저장 누적시간을 표시함
			if(m_bSaveStarted){
				m_elapseTime = tNow-m_startTime;
				m_strElapseTime = m_elapseTime.Format(L"%H:%M:%S");
			}
			
			m_bListUpdate = TRUE;  //스레드동작 플래그
			m_bDataWriteFlag = TRUE;
			
			for(int i=0; i<MAX_SENSORS; i++){
				int nId = m_sensorDatas[i].ID;
				if(nId > 0 && nId < MAX_SENSORS) //ID 유효성 검사
				{

					m_chartTemper.m_ChartData[i].Add(0,m_sensorDatas[i].TEMPERATURE
						,tNow.GetHour(), tNow.GetMinute(), tNow.GetSecond(), tNow.GetYear(), tNow.GetMonth(), tNow.GetDay());
					m_chartHumi.m_ChartData[i].Add(0,m_sensorDatas[i].HUMIDITY
						,tNow.GetHour(), tNow.GetMinute(), tNow.GetSecond(), tNow.GetYear(), tNow.GetMonth(), tNow.GetDay());
				}					
			}

			m_chartTemper.m_bWarningMove = true;
			m_chartHumi.m_bWarningMove = true;
			m_chartTemper.RedrawWindow();			
			m_chartHumi.RedrawWindow();

			//  [6/17/2012 Bume]
			//냄새를 분석한다.
			float currentHumi = m_sensorDatas[m_cComboIDSelect.GetCurSel()].HUMIDITY;
			//float temper1 = m_sensorDatas[2].TEMPERATURE;			// 3번 센서의 온도
			//float temper2 = m_sensorDatas[11].TEMPERATURE;			// 12번 센서의 온도
			//float temper3 = m_sensorDatas[0].TEMPERATURE;			// 1번 센서의 온도
			float temper1=0,temper2=0;
			if(currentHumi < 0 || currentHumi > 100) currentHumi = 0;		//유효하지 않은 데이터 삽입을 방지한다. 0으로 처리
			//로직을 선택한다.
			m_nLogic = m_cComboSelectLogic.GetCurSel()+1;
			if(m_nLogic == LOGIC_1){
				//m_cEditLogicValue.EnableWindow(FALSE);
				//m_cComboIDSelect.EnableWindow(TRUE);
				//m_cComboIDSelect2.EnableWindow(FALSE);
			}
			else if(m_nLogic == LOGIC_4){
				//m_cEditLogicValue.EnableWindow(TRUE);
				//m_cComboIDSelect.EnableWindow(FALSE);	
				//m_cComboIDSelect2.EnableWindow(FALSE);
				temper1 = m_sensorDatas[2].TEMPERATURE;			// 3번 센서의 온도
				temper2 = m_sensorDatas[11].TEMPERATURE;			// 12번 센서의 온도
				currentHumi = m_sensorDatas[11].HUMIDITY;
			}
			else if(m_nLogic == LOGIC_5){
				//m_cEditLogicValue.EnableWindow(TRUE);
				//m_cComboIDSelect.EnableWindow(FALSE);
				//m_cComboIDSelect2.EnableWindow(FALSE);
				temper1 = m_sensorDatas[0].TEMPERATURE;				// 1번 센서의 온도
				temper2 = m_sensorDatas[11].TEMPERATURE;			// 12번 센서의 온도
				currentHumi = m_sensorDatas[11].HUMIDITY;
			}
			else if(m_nLogic ==  LOGIC_6){
				//m_cEditLogicValue.EnableWindow(FALSE);
				//m_cComboIDSelect.EnableWindow(TRUE);
				//m_cComboIDSelect2.EnableWindow(TRUE);
				temper1 = m_sensorDatas[m_cComboIDSelect.GetCurSel()].TEMPERATURE;			// 1 선택센서
				temper2 = m_sensorDatas[m_cComboIDSelect2.GetCurSel()].TEMPERATURE;			// 2 선택센서				
			}
			else if(m_nLogic ==  LOGIC_7){
				temper1 = m_sensorDatas[m_cComboIDSelect.GetCurSel()].TEMPERATURE;			// 1 선택센서
				temper2 = m_sensorDatas[m_cComboIDSelect2.GetCurSel()].TEMPERATURE;			// 2 선택센서				
			}

			else{				
				m_cEditLogicValue.EnableWindow(TRUE);
				m_cComboIDSelect.EnableWindow(TRUE);
			}

			// 로직 변수를 읽는다.
			CString strLogicValue=L"";
			m_cEditLogicValue.GetWindowText(strLogicValue);
			m_nLogicVariable = _wtof(strLogicValue);			
			//분석시작
			m_nAnalysisResult = OdorAnalysis(currentHumi,temper1,temper2);
			// 냄새 알람을 해준다.
			if(m_nAnalysisResult >= LV_1 ){
				//알람소리를 껐다가
				//PlaySound(NULL,NULL,NULL);
				// 1단계 일때는 2초에 1번 알람
				if(m_nAnalysisResult == LV_1)
				{
					if(tNow.GetSecond()%2 == 0)
						PlaySound(MAKEINTRESOURCE(IDR_WAVE_ALRAM2),NULL,SND_ASYNC | SND_RESOURCE);				
				}
				// 2단계 일때는 1초에 1번 알람
				if(m_nAnalysisResult == LV_2)
					PlaySound(MAKEINTRESOURCE(IDR_WAVE_ALRAM2),NULL,SND_ASYNC | /*SND_LOOP |*/ SND_RESOURCE);				
			}
			//else
				//PlaySound(NULL,NULL,NULL);		
					

			//TextOut 영역만 화면을 다시그린다.
			CRect rt;
			rt.top = 85; rt.bottom=150; rt.left = 60; rt.right = 150;
			InvalidateRect(rt,FALSE);
			rt.top = 250; rt.bottom=300; rt.left = 250; rt.right = 450;
			InvalidateRect(rt,FALSE);

		}		
	}
	CDialogEx::OnTimer(nIDEvent);
}

void CMainFormDlg::OnDestroy()
{
	CDialogEx::OnDestroy();

	// TODO: 여기에 메시지 처리기 코드를 추가합니다.
	TerminateThread(m_pListupThread->m_hThread,0);
	TerminateThread(m_pLoggingThread->m_hThread,0);	
}

void CMainFormDlg::OnCustomdrawList(NMHDR* pNMHDR, LRESULT* pResult)
{
	NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>(pNMHDR);
	*pResult = 0;

	if(CDDS_PREPAINT == pLVCD->nmcd.dwDrawStage){
		*pResult = CDRF_NOTIFYITEMDRAW;
	}
	else if(CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage){		
		if((pLVCD->nmcd.dwItemSpec %2) == 0){			
			pLVCD->clrText = RGB(0,0,0);
			pLVCD->clrTextBk = RGB(230,230,230);
		}
		else{
			pLVCD->clrText = RGB(0,0,0);
			pLVCD->clrTextBk = RGB(255,255,255);		
		}
		*pResult = CDRF_DODEFAULT;
	}	
}

void CMainFormDlg::OnBnClickedButtonEmergency()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	//m_bEmergency_listflag = TRUE;
	m_nEmergency_logflag = 1;
	
	m_cListTemper.SetItemText(0,1,L"  X");
	m_cListHumi.SetItemText(0,1,L"  X");
	m_chartTemper.SetWarning();	
	m_chartHumi.SetWarning();
}


void CMainFormDlg::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	// TODO: 여기에 메시지 처리기 코드를 추가합니다.
	// 그리기 메시지에 대해서는 CDialogEx::OnPaint()을(를) 호출하지 마십시오.
	
	CBitmap bmp;
	CDC memDC;
	memDC.CreateCompatibleDC(&dc);
	bmp.LoadMappedBitmap(IDB_BITMAP_BGIMG3);

	CBitmap *pOldbmp = (CBitmap *)memDC.SelectObject(&bmp);

	BITMAP bmpinfo;
	bmp.GetBitmap(&bmpinfo);
	 
	//Text Draw =======================================================================
	//memDC.TextOutW(10,150,L"COM1,연결됨");
	//연결상태
	textDraw(&memDC, m_strCommState,60,85,25,RGB(0x31,0x61,0xea));
	//동작시간
	textDraw(&memDC, m_strElapseTime,60,153,25,RGB(0x31,0x61,0xea));
	//데이터저장
	//textDraw(&memDC, L"자동저장",75,193,14,RGB(0x31,0x61,0xea));
	//  [6/17/2012 Bume]
	//분석상태	
	if(m_bAnalysis){		 
		if(m_nLogic == LOGIC_1){
			COLORREF clr = m_nAnalysisResult > 1? RGB(0xff,0x14,0x22) : m_nAnalysisResult == 1? RGB(0xff,0x7e,0x00): RGB(0x31,0x61,0xea);
			textDraw(&memDC, m_strAnalysisMsg[m_nAnalysisResult],270,305,14,clr);
		}
		else if(m_nLogic == LOGIC_6 || m_nLogic == LOGIC_7){
			int tmpLv = m_nAnalysisResult >= 1? 1 : 0;
			COLORREF clr = tmpLv == 1? RGB(0xff,0x14,0x22) : RGB(0x31,0x61,0xea);
			textDraw(&memDC, m_strAnalysisMsg2[tmpLv],270,305,14,clr);
		}
		else{
			COLORREF clr = m_nAnalysisResult == 1? RGB(0xff,0x14,0x22) : RGB(0x31,0x61,0xea);
			textDraw(&memDC, m_strAnalysisMsg2[m_nAnalysisResult],270,305,14,clr);
		}
		
	}
	else
		textDraw(&memDC, L"분석 시작",270,305,14,RGB(0x31,0x61,0xea));
	//=================================================================================
	CRect rt;
	GetClientRect(&rt);
	//dc.BitBlt(0,-50,rt.Width(),rt.Height(),&memDC,0,0,SRCCOPY);
	dc.StretchBlt(-10,-25,rt.Width(),rt.Height(),&memDC,0,0,bmpinfo.bmWidth,bmpinfo.bmHeight,SRCCOPY);
	
	memDC.SelectObject(pOldbmp);
	bmp.DeleteObject();
}

void CMainFormDlg::textDraw(CDC *pDC, CString msg, float x, float y, float fntsize,COLORREF clr)
{
	/////////////////////////////textdraw/////////////////////////////
	CFont font;
	font.CreateFont( fntsize,						// 폰트 높이를 논리적 단위로 지정, 0이면 기본 값)
		0,											// 폰트 폭지정, 0이면 폰트dml 장평이 일정하다.
		0,											// 폰트 각도를 0.1도 단위로 설정, 360분법으로 3시 방향이 0도이다.
		0,											// 글자 한 자와 X축과의 각도 지정
		800,									// 폰트의 두께 0~1000사이 값으로 지정(기본400)
		FALSE,										// 기울임체를 할꺼냐?
		FALSE,										// 밑줄을 칠꺼냐?
		0,											// 관통선
		ANSI_CHARSET,								// 문자 셋을 설정, ANI_CHARSET(통상 윈도우), HANGEUL_CHARSET, OEM_CHARSET
		OUT_DEFAULT_PRECIS,							// 출력 정확도
		CLIP_DEFAULT_PRECIS,						// 클리핑 정확도
		DEFAULT_QUALITY,							// 논리적 폰트를 물리적 폰트에 얼마나 근접시킬 것인가를 지정
		DEFAULT_PITCH | FF_SWISS,					// 폰트의 피치와그룹 설정
		L"Thoma") ;								// 글꼴의 이름을 나타내는 문자열을 설정
	CFont* oldfont = pDC->SelectObject(&font);	
	pDC->SetTextColor(clr);
	pDC->TextOutW(x,y,msg);
	pDC->SelectObject(oldfont);
	font.DeleteObject();
	///////////////////////////////////////////////////////////////////
}

HBRUSH CMainFormDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);

	// TODO:  여기서 DC의 특성을 변경합니다.

	if(nCtlColor == CTLCOLOR_STATIC)
	{
		if(pWnd->GetDlgCtrlID() == IDC_RADIO_TEMPER || IDC_RADIO_HUMI || IDC_CHECK_SETLOG)
		{
			pDC->SetBkMode(TRANSPARENT);		
			hbr = (HBRUSH)GetStockObject(NULL_BRUSH);
		}
	}
	if(nCtlColor == CTLCOLOR_EDIT)
	{
		int n = pWnd->GetDlgCtrlID();
		if(pWnd->GetDlgCtrlID() == IDC_COMBO_SELECTID)
		{
			pDC->SetBkMode(TRANSPARENT);		
			hbr = (HBRUSH)GetStockObject(NULL_BRUSH);
		}	
	}
	
	// TODO:  기본값이 적당하지 않으면 다른 브러시를 반환합니다.
	return hbr;
}

void CMainFormDlg::OnHdnItemclickListTemperature(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMHEADER phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.	
	*pResult = 0;
	
	int nSensorId = phdr->iItem-2;

	if(nSensorId < 0)
		return;
	m_bShowGraph[nSensorId] = !m_bShowGraph[nSensorId];

	m_chartTemper.m_ChartData[nSensorId].m_config.bShowDataLine = m_bShowGraph[nSensorId];
	m_chartHumi.m_ChartData[nSensorId].m_config.bShowDataLine = m_bShowGraph[nSensorId];
}


void CMainFormDlg::OnStnClickedStaticImage()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	theApp.OnAppAbout();
}


void CMainFormDlg::OnBnClickedButtonLogopen()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.	
	//ShellExecute(NULL, L"open",_T(LOGPATH), NULL, NULL, SW_SHOW);
	CDataLoadDlg *pDlg = new CDataLoadDlg();
	pDlg->Create(IDD_DATALOAD_DLG);
	pDlg->ShowWindow(SW_SHOW);
}


void CMainFormDlg::OnBnClickedButtonLogstart()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.	
 	CFileNameInpuDlg dlg;

	m_bSaveStarted = !m_bSaveStarted;

	if(m_bSaveStarted)
	{
		if(dlg.DoModal() == IDOK){
			m_strLogFileName = dlg.m_strFileName; 
		}

		m_cLogsaveStartbtn.LoadBitmaps(IDB_LOGSAVEEND_DIS,IDB_LOGSAVEEND_SEL,NULL,IDB_LOGSAVEEND_DIS);
		m_startTime = COleDateTime::GetCurrentTime();
		m_bSaveFlag = TRUE;
		m_cLogsaveStartbtn.RedrawWindow();
	}
	else
	{
		m_cLogsaveStartbtn.LoadBitmaps(IDB_LOGSAVESTART_DIS,IDB_LOGSAVESTART_SEL,NULL,IDB_LOGSAVESTART_DIS);
		m_cLogsaveStartbtn.RedrawWindow();
	}


}


void CMainFormDlg::OnOK()
{
	// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.

	//CDialogEx::OnOK();
}


void CMainFormDlg::OnCancel()
{
	// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.

	//CDialogEx::OnCancel();
}


void CMainFormDlg::OnBnClickedButtonAnalysis()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	
	//통신이 연결되어 있다면
	if(m_comm.m_bConnected)
	{
		m_bAnalysis = !m_bAnalysis;	
		m_nLogic_state_flag = LV_0;
		if(m_bAnalysis){			
			m_cBtnAnalysis.LoadBitmaps(IDB_BTNANALYSIS_E_DIS,IDB_BTNANALYSIS_E_SEL,NULL,IDB_BTNANALYSIS_E_DIS);
		}
		else
			m_cBtnAnalysis.LoadBitmaps(IDB_BTNANALYSIS_S_DIS,IDB_BTNANALYSIS_S_SEL,NULL,IDB_BTNANALYSIS_S_DIS);
	}
	else
	{
		m_bAnalysis = FALSE;
		m_cBtnAnalysis.LoadBitmaps(IDB_BTNANALYSIS_S_DIS,IDB_BTNANALYSIS_S_SEL,NULL,IDB_BTNANALYSIS_S_DIS);
	}

	m_cBtnAnalysis.Invalidate();

}

int CMainFormDlg::OdorAnalysis(float currenthumidity, float temper1, float temper2)
{
	int nAnalysisResult = 0;
	float nValiddata_one = 0, nValiddata_two = 0;	

	//선택한 로직에 따라 다른 알고리즘이 적용됨
	if(m_bAnalysis){
		switch(m_nLogic){
		case LOGIC_1:
			{
				//로직 1
				// 1. 습도 최대값을 갱신한다.
				m_maxHumidity = m_maxHumidity < currenthumidity ? currenthumidity : m_maxHumidity ;

				// 2. 알고리즘에 적용한다.		
				nValiddata_one = (0.88 * m_maxHumidity) + 10.33;
				nValiddata_two = (0.825 * m_maxHumidity) + 14.43;

				// 3. 유효값과 비교한다.
				if(currenthumidity <= nValiddata_one && currenthumidity > nValiddata_two)
					nAnalysisResult = LV_1;
				else if(currenthumidity <= nValiddata_two && currenthumidity > 75)
					nAnalysisResult = LV_2;
				else if(currenthumidity <= 75)
					nAnalysisResult = LV_0;
				else
					nAnalysisResult = LV_0;
			}
			break;
			//LOGIC_1 end
		case LOGIC_2:
			{
				// 로직 2: (max 습도 - [입력값]) 값을 냄새발생 기준값으로 활용 (2단계 검출)
				// 1. 습도 최대값을 갱신한다.
				m_maxHumidity = m_maxHumidity < currenthumidity ? currenthumidity : m_maxHumidity ;
				// 2. 알고리즘에 적용한다.		
				nValiddata_one = m_maxHumidity - m_nLogicVariable;
				// 3. 유효값과 비교 한다.
				if(currenthumidity <= nValiddata_one){
					if(currenthumidity <= 80)
						nAnalysisResult = LV_0;
					else
						nAnalysisResult = LV_1;
				}
				else
					nAnalysisResult = LV_0;
			}
			break;
			//LOGIC_2 end
		case LOGIC_3:
			{
				// 로직 3: 현재의 습도값이 임의값보다 낮은지를 비교하는 절대량 비교식 (2단계 검출)
				// 1. 습도 최대값을 갱신한다.
				m_maxHumidity = m_maxHumidity < currenthumidity ? currenthumidity : m_maxHumidity ;
				// 2. 알고리즘에 적용한다.		
				nValiddata_one = m_nLogicVariable;
				// 3. 유효값과 비교 한다.
				if(currenthumidity <= nValiddata_one){
					if(currenthumidity <= 80)
						nAnalysisResult = LV_0;
					else
						nAnalysisResult = LV_1;
				}
				else
					nAnalysisResult = LV_0;
				
			}
			break;
			//LOGIC_3 end
		case LOGIC_4:
			{	
				// 로직 4: #3, #12의 온도차이에 의한 비교
				// 1. 유효값 설정
				nValiddata_one = m_nLogicVariable;
				// 2. 유효값과 비교
				if((temper2 - temper1) >= nValiddata_one){
					if(currenthumidity <= 80)
						nAnalysisResult = LV_0;
					else
						nAnalysisResult = LV_1;
				}
				else
					nAnalysisResult = LV_0;
			}
			break;
			//LOGIC_4 end
		case LOGIC_5:
			{	
				// 로직 5: #1, #12의 온도차이에 의한 비교
				// 1. 유효값 설정
				nValiddata_one = m_nLogicVariable;
				// 2. 유효값과 비교
				if((temper2 - temper1) >= nValiddata_one){
					if(currenthumidity <= 80)
						nAnalysisResult = LV_0;
					else
						nAnalysisResult = LV_1;
				}
				else
					nAnalysisResult = LV_0;
			}
			break;
			//LOGIC_5 end
			//완결판
			case LOGIC_6:
				{
					// 로직 6: #n, #m 의 온도차이에 의한 비교
					//0. data shift
					m_Logic6_Temper1[0] = m_Logic6_Temper1[1];
					m_Logic6_Temper1[1] = temper1;
					m_Logic6_Temper2[0] = m_Logic6_Temper2[1];
					m_Logic6_Temper2[1] = temper2;

										
					switch(m_nLogic_state_flag){
					case LV_0:
						if(m_Logic6_Temper1[0] == m_Logic6_Temper2[0]){

							if(m_Logic6_Temper1[1] - m_Logic6_Temper2[1] < -0.09){
								m_nLogic_state_flag = LV_1;
								nAnalysisResult = LV_2;
							}
							else{

							}
						}
						else{
							if(m_Logic6_Temper1[0] - m_Logic6_Temper2[0] > 0.09){
								if(m_Logic6_Temper1[1] - m_Logic6_Temper2[1] < -0.39){								
									m_nLogic_state_flag = LV_1;
									nAnalysisResult = LV_2;
								}
								else{									
								}
							}
							else{								
							}
						}
						break;
					case LV_1:
						if(m_Logic6_Temper1[1] - m_Logic6_Temper2[1] > 0.09){							
//로직 종료		
							nAnalysisResult = LV_0;
							OnBnClickedButtonAnalysis();	//분석 버튼을 반전시켜 종료시킨다
							m_nLogic_state_flag = LV_0;
						}
						else{
							nAnalysisResult = LV_2;
						}
						break;
					default:
						break;
					}
				}
					/*
					//1. 알람중인지 체크
					if(nAnalysisResult >= LV_2){
						if(m_Logic6_Temper1[1] - m_Logic6_Temper2[1] > 0.09){
							nAnalysisResult = LV_0;
						}
						else{
							nAnalysisResult = LV_2;
						}
					}
					//2. 알람중이 아니라면 검사
					else{
						if(m_Logic6_Temper1[0] == m_Logic6_Temper2[0]){

							if(m_Logic6_Temper1[1] - m_Logic6_Temper2[1] < -0.09){
								nAnalysisResult = LV_2;
							}
							else{
								nAnalysisResult = LV_0;
							}
						}
						else{
							if(m_Logic6_Temper1[0] - m_Logic6_Temper2[0] > 0.09){

								if(m_Logic6_Temper1[1] - m_Logic6_Temper2[1] < -0.39){								
									nAnalysisResult = LV_2;
								}
								else{
									nAnalysisResult = LV_0;
								}
							}
							else{
								nAnalysisResult = LV_0;
							}
						}

					}
					
				}
				*/
				break;
				//LOGIC_6 end
				//final final 로직
			case LOGIC_7:
				{					
					// 로직 7: #n, #m의 온도차이에 의한 비교
					// 1. 유효값 설정
					nValiddata_one = m_nLogicVariable;
					//TRACE(L"temper1[%.2f],temper2[%.2f],valid[%.2f],flag[%d]\r\n" , temper1,temper2,nValiddata_one,m_nLogic_state_flag );
					//TRACE(L"temper1[%.2f],temper2[%.2f],flag[%d]\r\n" , temper1,temper2,m_nLogic_state_flag );
					switch(m_nLogic_state_flag){
					case LV_0:
						// 1. 온도차이 비교
						if(temper1 - temper2 >= -0.2){
							m_nLogic_state_flag = LV_1;
						}
						else{

						}
						break;
					case LV_1:
						if(temper1 - temper2 <= nValiddata_one){
							nAnalysisResult = LV_2;
							m_nLogic_state_flag = LV_2;
						}
						else{
							
						}

						break;
					case LV_2:
						if(temper1 - temper2 >= 0.1){
							//로직 종료		
							nAnalysisResult = LV_0;
							OnBnClickedButtonAnalysis();	//분석 버튼을 반전시켜 종료시킨다
							m_nLogic_state_flag = LV_0;											
						}
						else{
							nAnalysisResult = LV_2;
						}
						break;
					default :
						break;
					}
				}
				break;
				//LOGIC_7 end
		default:
			break;
		}
	}
	else{ 
		// 분석 실시 하지 않음
		m_maxHumidity = 0;
	}

	return nAnalysisResult;
}

void CMainFormDlg::OnCbnSelchangeComboSelectid()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	m_nLogic = m_cComboSelectLogic.GetCurSel()+1;
	if(m_bAnalysis){
		if(m_nLogic == LOGIC_6 || m_nLogic == LOGIC_7){
			AfxMessageBox(L"현재 분석중입니다. 분석을 종료하고 로직을 선택하십시오.");
			return;
		}		
	}
	m_maxHumidity = 0;
	m_Logic6_Temper1[0]=0;
	m_Logic6_Temper1[1]=0;
	m_Logic6_Temper2[0]=0;
	m_Logic6_Temper2[1]=0;
}

void CMainFormDlg::OnCbnSelchangeComboSelectid2()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	m_nLogic = m_cComboSelectLogic.GetCurSel()+1;
	if(m_bAnalysis){
		if(m_nLogic == LOGIC_6 || m_nLogic == LOGIC_7){
			AfxMessageBox(L"현재 분석중입니다. 분석을 종료하고 로직을 선택하십시오.");
			return;
		}		
	}
	m_maxHumidity = 0;
	m_Logic6_Temper1[0]=0;
	m_Logic6_Temper1[1]=0;
	m_Logic6_Temper2[0]=0;
	m_Logic6_Temper2[1]=0;
}

void CMainFormDlg::OnCbnSelchangeComboSelectlogic()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	if(m_bAnalysis){
		AfxMessageBox(L"현재 분석중입니다. 분석을 종료하고 로직을 선택하십시오.");
		return;
	}
	m_nLogic = m_cComboSelectLogic.GetCurSel()+1;
	if(m_nLogic == LOGIC_1){
		m_cEditLogicValue.ShowWindow(SW_HIDE);
		m_cComboIDSelect.ShowWindow(SW_SHOW);
		m_cComboIDSelect2.ShowWindow(SW_HIDE);
	}
	else if(m_nLogic == LOGIC_4){
		m_cEditLogicValue.ShowWindow(SW_SHOW);
		m_cComboIDSelect.ShowWindow(SW_HIDE);
		m_cComboIDSelect2.ShowWindow(SW_HIDE);
	}
	else if(m_nLogic == LOGIC_5){
		m_cEditLogicValue.ShowWindow(SW_SHOW);
		m_cComboIDSelect.ShowWindow(SW_HIDE);
		m_cComboIDSelect2.ShowWindow(SW_HIDE);
	}
	else if(m_nLogic ==  LOGIC_6){
		m_cEditLogicValue.ShowWindow(SW_HIDE);
		m_cComboIDSelect.ShowWindow(SW_SHOW);
		m_cComboIDSelect.SetCurSel(0);
		m_cComboIDSelect2.ShowWindow(SW_SHOW);
		m_cComboIDSelect2.SetCurSel(0);
	}
	else if(m_nLogic ==  LOGIC_7){
		m_cEditLogicValue.ShowWindow(SW_SHOW);
		m_cEditLogicValue.SetWindowTextW(L"-0.2");
		m_cComboIDSelect.ShowWindow(SW_SHOW);
		m_cComboIDSelect.SetCurSel(0);
		m_cComboIDSelect2.ShowWindow(SW_SHOW);
		m_cComboIDSelect2.SetCurSel(0);
	}
	else{				
		m_cEditLogicValue.ShowWindow(SW_SHOW);
		m_cComboIDSelect.ShowWindow(SW_SHOW);
		m_cComboIDSelect2.ShowWindow(SW_HIDE);
	}
}


void CMainFormDlg::OnCbnSetfocusComboSelectid2()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	m_nLogic = m_cComboSelectLogic.GetCurSel()+1;
	if(m_bAnalysis){
		if(m_nLogic == LOGIC_6 || m_nLogic == LOGIC_7){
			AfxMessageBox(L"현재 분석중입니다. 분석을 종료하고 로직을 선택하십시오.");
			return;
		}		
	}
}


void CMainFormDlg::OnCbnSetfocusComboSelectid()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
	m_nLogic = m_cComboSelectLogic.GetCurSel()+1;
	if(m_bAnalysis){
		if(m_nLogic == LOGIC_6 || m_nLogic == LOGIC_7){
			AfxMessageBox(L"현재 분석중입니다. 분석을 종료하고 로직을 선택하십시오.");
			return;
		}		
	}
}


void CMainFormDlg::OnCbnSetfocusComboSelectlogic()
{
	// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.	
	if(m_bAnalysis){		
		AfxMessageBox(L"현재 분석중입니다. 분석을 종료하고 로직을 선택하십시오.");
		return;
	}
}
